package com.tyjc.unique.ssq;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.tyjc.unique.AnaylaseBaseFragment;
import com.tyjc.unique.net.StringResultBean_New;
import com.tyjc.unique.util.SSQ_ZhuShu;
import com.tyjc.unique.view.RandomSetView;
import com.fyzk.activity.lottery.shuzicai.BallInfo;
import com.fyzk.activity.lottery.shuzicai.SelectBallView;
import com.fyzk.activity.lottery.shuzicai.TouZhuHelper;
import com.fyzk.activity.myview.WeiZhi;
import com.fyzk.bean.CurrentPhaseInfo;
import com.fyzk.bean.HistoryPrizeResponse;
import com.fyzk.bean.PrizeHistoryItem;
import com.fyzk.bean.PrizeLevel;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.net.Constants;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.utils.RandomUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;

//import com.fyzk.betzhushu.ssq.SSQ_ZhuShu;

/**
 * Created by miao on 16/6/28.
 */
@ContentView(R.layout.fg_ssqverifyprize)
public class SSQVerifyPrizeFragment extends AnaylaseBaseFragment implements
        RandomSetView.RandomBtnClickListener, TouZhuHelper.BallItemClickLitener, TouZhuHelper
        .BallClickListener {


    @ViewInject(R.id.randomSet_red)
    RandomSetView randomSet_red;

    @ViewInject(R.id.randomSet_blue)
    RandomSetView randomSet_blue;

    @ViewInject(R.id.redball)
    SelectBallView redball;

    @ViewInject(R.id.blueball)
    SelectBallView blueball;

    @ViewInject(R.id.txt_zhushu)
    TextView txt_zhushu;

    @ViewInject(R.id.btn_compute)
    Button btn_compute;


    private long zhushu;

    private Dialog bigdataDialog;

    private int currentPhase;//当前投注期

    private String[] datas = {"2003.txt", "2004.txt", "2005.txt", "2006.txt", "2007.txt", "2008" +
            ".txt", "2009.txt", "2010.txt", "2011.txt", "2012.txt", "2013.txt", "2014.txt", "2015" +
            ".txt", "2016.txt","2017.txt"};


    ArrayList<String> red_code = new ArrayList<>();
    ArrayList<String> blue_code = new ArrayList<>();


    ArrayList<PrizeItem[]> prizeArrs = new ArrayList<>();

    protected List<BallInfo> redBallInfos = new ArrayList<BallInfo>();
    protected List<BallInfo> blueBallInfos = new ArrayList<BallInfo>();
    protected List<List<BallInfo>> arrs = new ArrayList<List<BallInfo>>();


    private final int MAX_RED = 16;
    //分析dialog 中的数据项
    TextView txt_bigdata_analyze = null;
    TextView txt_compute_result = null;
    TextView txt_compute_result_2 = null;
    TextView bet_dialog = null;


    @Override
    public void showData() {
        super.showData();
        TouZhuHelper.getInstance().setBallClickListener(this);
        TouZhuHelper.getInstance().setBallItemClickLitener(this);
        com.fyzk.utils.LogUtil.v("showData>>>>>>>>>>>>>>>>");
        findCurrentPhase();

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        topView.setOnTopTitleClickLitener(this);
        initBallList();
        redball.setBallInfoList(redBallInfos);
        redball.setSelect_max(MAX_RED);
        blueball.setBallInfoList(blueBallInfos);
        btn_compute.setOnClickListener(this);
        initRandomSetView();

    }


    //初始化与小球界面绑定的数据
    private void initBallList() {
        initBallList(redBallInfos, 33, 1, true);
        initBallList(blueBallInfos, 16, 1, true);
        arrs.add(redBallInfos);
        arrs.add(blueBallInfos);
    }

    //设置机选view
    public void initRandomSetView() {
        randomSet_red.setOnRandomBtnClickListener(this);
        randomSet_blue.setOnRandomBtnClickListener(this);
        randomSet_red.setTag_line("红球",R.drawable.ball_red);
        randomSet_blue.setTag_line("蓝球",R.drawable.ball_blue);
    }

    @Override
    public void onStart() {
        super.onStart();
        com.fyzk.utils.LogUtil.v("onStart>>>>>>>>>>>>>>>>");
    }

    @Override
    public void onResume() {
        super.onResume();
        com.fyzk.utils.LogUtil.v("onStart>>>>>>>>>>>>>>>>");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        com.fyzk.utils.LogUtil.v("onDetach>>>>>>>>>>>>>>>>");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        findCurrentPhase();
        com.fyzk.utils.LogUtil.v("onAttach context>>>>>>>>>>>>>>>>");
        TouZhuHelper.getInstance().setBallItemClickLitener(this);
        TouZhuHelper.getInstance().setBallClickListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        com.fyzk.utils.LogUtil.v("onPause >>>>>>>>>>>>>>>>");
    }


    /**
     * 获取开奖信息
     */
    private void getKaiJiang(int phase) {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", LotteryIDUtils.SSQ_LOTTERY_ID_INT);
            params.put("pageIndex", 1);
            params.put("maxResult", phase);//SchemaDef
            // .HISTORY_LOTTERY
            httpPostJson(CommandUtil.HISTORY_LOTTERY, Commands.WINCODEHISTORY, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void findCurrentPhase() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", LotteryIDUtils.SSQ_LOTTERY_ID_INT);
            httpPostJson(CommandUtil.FINDCURRENTPHASE, Commands.FINDCURRENTPHASE, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化 小球list
     *
     * @param balls
     * @param count 每列显示小球数
     * @param start
     */
    public void initBallList(List<BallInfo> balls, int count, int start,
                             boolean hasZero) {
        balls.clear();
        for (int j = start; j < count + start; j++) {
            BallInfo qiu;
            if (hasZero) {
                if (j < 10) {
                    qiu = new BallInfo("0" + j);
                } else {
                    qiu = new BallInfo("" + j);
                }
            } else {
                qiu = new BallInfo(String.valueOf(j));
            }
            balls.add(qiu);
        }
    }

    @Override
    public void onRandomBtnClick(RandomSetView v, int randomCount) {
        switch (v.getId()) {
            case R.id.randomSet_red:
                int redArr[] = RandomUtil.randomNoRepeat(randomCount, 0, 33);
                initBallList(redBallInfos, 33, 1, true);
                for (int i = 0; i < redArr.length; i++) {
                    redBallInfos.get(redArr[i]).setSelected(true);
                }
                redball.invalidate();
                break;
            case R.id.randomSet_blue:
                int blueArr[] = RandomUtil.randomNoRepeat(randomCount, 0, 16);
                initBallList(blueBallInfos, 16, 1, true);
                for (int i = 0; i < blueArr.length; i++) {
                    blueBallInfos.get(blueArr[i]).setSelected(true);
                }
                blueball.invalidate();
                break;

            default:
                break;
        }
        ballClick(null);
    }


    public void ballClick(WeiZhi wz) {
        zhushu = new SSQ_ZhuShu().betZhuShu(arrs);
        txt_zhushu.setText("总计，" + zhushu + "注 " + zhushu * 2 + "米");
        red_code.clear();
        blue_code.clear();
        for (BallInfo info : redBallInfos) {
            if (info.isSelected()) {
                red_code.add(info.getNum());
            }
        }
        for (BallInfo info : blueBallInfos) {
            if (info.isSelected()) {
                blue_code.add(info.getNum());
            }
        }

    }

    @Override
    public void ballClick() {
        ballClick(null);
    }


    class PrizeItem {
        String phase;
        String date;
        String[] red;
        String blue;
    }


    public void readFromInternal() {
        long time1 = System.currentTimeMillis();
        try {

            for (int i = 0; i < datas.length; i++) {
                AssetManager am = null;
                am = getActivity().getAssets();
                InputStream is = am.open(datas[i]);
                byte[] b = new byte[1024];
                int index = 0;
                StringBuffer buffer = new StringBuffer();
                while ((index = is.read(b)) > 0) {
                    String str = new String(b, 0, index);
                    buffer.append(str);
                }
                String[] items = buffer.toString().split(";");
                PrizeItem[] prizeItems = new PrizeItem[items.length];
                for (int s = 0; s < items.length; s++) {
                    LogUtil.v(items[s]);
                    items[s] = items[s].replace("    ", "~");
                    String[] prizeStr = items[s].split("~");
                    PrizeItem item = new PrizeItem();
                    item.phase = prizeStr[0];
                    item.date = prizeStr[2];
                    String[] prize_code = prizeStr[1].split("\\|");
                    item.blue = prize_code[1];
                    item.red = prize_code[0].split(",");
                    prizeItems[s] = item;
                }
                prizeArrs.add(prizeItems);
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.v(prizeArrs.size() + "<<<<<<<<<<<<");
        }

        long time2 = System.currentTimeMillis();
    }


    private void compute() {
        ArrayList<PrizeLevel> levels = new ArrayList<>();
        int prize1 = 0;
        int prize2 = 0;
        int prize3 = 0;
        int prize4 = 0;
        int prize5 = 0;
        int prize6 = 0;
        for (int p = 0; p < prizeArrs.size(); p++) {
            LogUtil.d("" + p + ">" + prizeArrs.get(p).length);
            for (PrizeItem item : prizeArrs.get(p)) {

                ArrayList<String> red_strs = new ArrayList<>();
                for (String aa : item.red) {
                    red_strs.add(aa);
                }
                red_strs.retainAll(red_code);
                if (blue_code.contains(item.blue)) {


                    switch (red_strs.size()) {
                        case 6: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 1;
                            prize1++;
                            level.prizeAmt = 5000000;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                        case 5: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 3;
                            prize3++;
                            level.prizeAmt = 3000;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                        case 4: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 4;
                            level.prizeAmt = 200;
                            prize4++;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                        case 3: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 5;
                            prize5++;
                            level.prizeAmt = 10;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                        default: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 6;
                            level.prizeAmt = 5;
                            prize6++;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                    }


                } else {
                    switch (red_strs.size()) {
                        case 6: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 2;
                            prize2++;
                            level.prizeAmt = 2000000;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                        case 5: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 4;
                            level.prizeAmt = 200;
                            prize4++;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                        case 4: {
                            PrizeLevel level = new PrizeLevel();
                            level.prizeLevel = 5;
                            prize5++;
                            level.prizeAmt = 10;
                            level.phase = item.phase;
                            levels.add(level);
                        }
                        break;
                    }
                }
            }
        }
        StringBuffer info = new StringBuffer();
        info.append("我们奖您选择的号码与双色球所有的历史开奖数据进行比对,");
        info.append("共中奖<font color=\"#33475f\"><b>" + levels.size() + "</b></font>次,其中:\n");
        StringBuffer info1 = new StringBuffer();
        boolean hasBig = false;
        if (prize1 > 0) {
            info1.append("一等奖<font color=\"#33475f\"><b>" + prize1 + "</b></font>次<br/>");
            hasBig = true;
        }
        if (prize2 > 0) {
            info1.append("二等奖<font color=\"#33475f\"><b>" + prize2 + "</b></font>次<br/>");
            if (!hasBig) {
                hasBig = true;
            }
        }
        if (prize3 > 0) {
            info1.append("三等奖<font color=\"#33475f\"><b>" + prize3 + "</b></font>次 单注奖金<font " +
                    "color=\"#eb4f38\"><b>3000</b></font>米<br/>");
        }
        if (prize4 > 0) {
            info1.append("四等奖<font color=\"#33475f\"><b>" + prize4 + "</b></font>次 单注奖金<font " +
                    "color=\"#eb4f38\"><b>200</b></font>米 <br/>");
        }
        if (prize5 > 0) {
            info1.append("五等奖<font color=\"#33475f\"><b>" + prize5 + "</b></font>次 单注奖金<font " +
                    "color=\"#eb4f38\"><b>10</b></font>米<br/>");
        }
        if (prize6 > 0) {
            info1.append("六等奖<font color=\"#33475f\"><b>" + prize6 + "</b></font>次 单注奖金<font " +
                    "color=\"#eb4f38\"><b>5</b></font>米<br/>");
        }


        if (bigdataDialog == null) {
            View view = View.inflate(getActivity(), R.layout.dialog_prize, null);
            txt_bigdata_analyze = (TextView) view.findViewById(R.id.txt_bigdata_analyze);
            txt_compute_result = (TextView) view.findViewById(R.id.txt_compute_result);
            txt_compute_result_2 = (TextView) view.findViewById(R.id.txt_compute_result_2);
            bet_dialog = (TextView) view.findViewById(R.id.dialog_prize_bet);
            TextView dialog_prize_ok = (TextView) view.findViewById(R.id.dialog_prize_ok);
            dialog_prize_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bigdataDialog.cancel();
                }
            });
            if(MySharedPreferences.getInstance().getOpenStatus()){
                bet_dialog.setVisibility(View.VISIBLE);
            }else{
                bet_dialog.setVisibility(View.GONE);
            }
            bigdataDialog = new Dialog(getActivity(), R.style.Theme_Light_Dialog);
            bigdataDialog.setContentView(view);
        }
        txt_compute_result_2.setText(Html.fromHtml(info1.toString()));
        txt_compute_result.setText(Html.fromHtml(info.toString()));
        if (hasBig) {
            txt_bigdata_analyze.setText("亲,这个号中过大奖了哦,放弃吧！");
        } else {
            txt_bigdata_analyze.setText("亲,这个号还没中过大奖,可以用！");
        }
        bet_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ssqBet(arrs, (int) zhushu);
            }
        });
        bigdataDialog.show();

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_read:
//                readFromInternal();
                break;
            case R.id.btn_compute:
                if (zhushu == 0) {
                    showToast("请至少选择6个红球,1个篮球");
                    return;
                }

                if (prizeArrs.size() == 13) {
                    showToast("未联网获取最新数据,测验结果可能不准确");
                }

                compute();
                break;
        }
    }


    @Override
    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDCURRENTPHASE:
                if (resultBean.getErrorcode().equals("0")) {
                    CurrentPhaseInfo info = JSON.parseObject(resultBean.getData(),
                            CurrentPhaseInfo.class);
                    currentPhase = Integer.parseInt(info.getPhase());
                    if (TextUtil.isEmpty(AppLotteryInfos.getPeriod(LotteryIDUtils.SSQ_LOTTERY_ID_INT))) {
                        AppLotteryInfos.setPeriod(LotteryIDUtils.SSQ_LOTTERY_ID_INT, info.getPhase());
                        AppLotteryInfos.setEndTime(LotteryIDUtils.SSQ_LOTTERY_ID_INT, info
                                .getEndSaleTime());
                    }
                    int phase = currentPhase - Constants.CURRENT_MAX_PHASE - 1;
                    LogUtil.d(phase + ">>>");
                    if (phase > 0) {
                        LogUtil.d(phase + ">>>");
                        getKaiJiang(phase);
                    }

                } else {
                    showToast(resultBean.getMsg());
                }

                break;
            case CommandUtil.HISTORY_LOTTERY:
                prizeArrs.clear();
                if (resultBean.getErrorcode().equals("0")) {
                    HistoryPrizeResponse info = JSON.parseObject(resultBean.getData(),
                            HistoryPrizeResponse.class);

                    PrizeItem[] prizeItems = new PrizeItem[info.wincodes.size()];
                    for (int i = 0; i < prizeItems.length; i++) {
                        PrizeItem item = new PrizeItem();
                        PrizeHistoryItem phi = info.wincodes.get(i);
                        String[] prizeStr = phi.wincode.split("\\|");
                        item.blue = prizeStr[1];
                        item.red = prizeStr[0].split(",");
                        item.date = phi.drawTime;
                        item.phase = phi.phase;
                        prizeItems[i] = item;
                    }
                    prizeArrs.add(prizeItems);
                    readFromInternal();
                } else {
                    showToast(resultBean.getMsg());
                }

                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String msg) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TouZhuHelper.getInstance().detachBallClickListener(this);
        TouZhuHelper.getInstance().detachBallItemClickListener(this);
    }
}
